package com.gui.juc.cas;

import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class CasABADemo {

    public static void main(String[] args) {

        AtomicReference<BigDecimal> atomicReference = new AtomicReference<>(new BigDecimal("10"));

        Thread t1 = new Thread(() -> {
            BigDecimal decimal1 = atomicReference.get();
            log.debug("第一次CAS前：{}", decimal1);
            boolean result = atomicReference.compareAndSet(decimal1, decimal1.subtract(new BigDecimal("1")));
            log.debug("第一次CAS后：{}， {}", result, atomicReference.get());
            Sleeper.sleep(2);
            BigDecimal decimal2 = atomicReference.get();
            log.debug("第二次CAS前：{}, {}", decimal2, atomicReference.get());
            boolean result2 = atomicReference.compareAndSet(decimal2, decimal2.subtract(new BigDecimal("1")));
            log.debug("第二次CAS：{}", result2);

        }, "t1");

        Thread t2 = new Thread(() -> {
            Sleeper.sleep(1);
            BigDecimal decimal1 = atomicReference.get();
            log.warn("第一次CAS前：{}", decimal1);
            boolean result = atomicReference.compareAndSet(decimal1, decimal1.add(new BigDecimal("1")));
            log.warn("第一次CAS：{}, {}", result, atomicReference.get());

        }, "t2");
        t1.start();
        t2.start();

        Sleeper.sleep(4);
        log.debug("最终结果：{}", atomicReference.get());
    }
}
